<?php
/*
 *资讯文章
*/
namespace App\Http\Controllers;

use App\Service\NewsService;
use App\Validation\ListValidation;

use App\Service\MemberPraiseService;
use App\Service\MemberCollectService;

class NewsController extends BaseController
{
	const DISPLAY_TRUE = 1;		//显示标识：是
	const DISPLAY_FALSE = 0;	//显示标识：否
	const COLLECT_TRUE = 1;		//收藏标识：是
	const COLLECT_FALSE = 0;	//收藏标识：否

	/**
	 * [indexAction 列表]
	 * @return [type] [description]
	 */
    public function indexAction()
    {
    	$this->getUser(0);

		$raw = $this->validation(new ListValidation, $this->request->getJsonRawBody());
		$raw->city_id = $this->city_id;
		$raw->is_display = self::DISPLAY_TRUE;
		$raw->member_id = property_exists($raw,'member_id') ? $raw->member_id : 0;
		// $data = NewsService::getList($raw);
		if (isset($raw->target_id) && $raw->target_id){
			$data = NewsService::getRecoList($raw);
		}else{
			$data = NewsService::getNewsList($raw);
		}
		//获取点赞和收藏
		$praise_data = [];
		$collect_data = [];
		if ($raw->member_id && $raw->member_id >0 && count($data) > 0){
			$groupId = 2;
			$id_arr = array_map('parent::getIdArray',$data);
			$praise_data  = MemberPraiseService::jugePraiseArr($raw->member_id, $groupId, $id_arr);
			$collect_data = MemberCollectService::jugeCollectArr($raw->member_id, $groupId, $id_arr);
		}

		$d = [];
		foreach ($data as $key => $value) {
			if (trim($value->title) == ''){
				continue;
			}
			unset($value->index_by);
			unset($value->reco_by);
			$d[$key] = $value;

			$d[$key]->is_collect = intval($value->is_collect) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;

			$album = [];
			if ($value->type_id == 5)
				$album = json_decode($value->album);

			$d[$key]->album = $album;

			//判断缩略图是否有图且url是否完整
			$d[$key]->thumb = $value->thumb ? $this->getFullUrl($value->thumb, FALSE, $this->config->imgurl) : $this->config->imgurl . '/uploads/default.png';

			$d[$key]->num  = (string)count($d[$key]->album);
			unset($d[$key]->ads_url_ios);
			unset($d[$key]->ads_url);
			$d[$key]->comment = $value->comment > 10000 ? floor($value->comment / 10000) . '万+' : $value->comment;
			$d[$key]->visit = $value->visit > 10000 ? floor($value->visit / 10000) . '万+' : $value->visit;
			$value->sources = explode('、', $value->sources)[0];
			$value->sources = (mb_strlen($value->sources,"UTF8") >16) ? mb_substr($value->sources,0,16,'utf-8') . '...' : mb_substr($value->sources,0,16,'utf-8');
			$d[$key]->sources = $value->sources ? $value->sources : "觅窝";

			if (strtotime($value->create_time) < strtotime(date("Y-m-d", time())) && $value->tags == 'new')
				$value->tags = '';
			// $d[$key]->ads_url = $value->create_time;
			// $d[$key]->ads_url_ios = date("Y-m-d H:i:s", time());
			$d[$key]->create_time = $this->getShowTime($value->create_time);
			$d[$key]->tags = $value->tags ? $value->tags : "";

			$d[$key]->is_praise  = in_array($value->id, $praise_data) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;
			$d[$key]->is_collect = in_array($value->id, $collect_data) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;

			$d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id;
			if ($value->cont_type != 1){//广告类的资讯
				$d[$key]->go_url = $value->ads_url;
			}else{
				$is_praise = $d[$key]->is_praise ? 1 : 0;
				// $d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id . '/' . $value->groupId . '/' . $is_praise;
				$d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id;
			}
			
			//第三方url
			$d[$key]->three_url = $value->three_url ? $value->three_url : $d[$key]->go_url;
			$value->pics ="";
			$pics = [];
			$pics = explode(',', $value->pics);
			$pics = array_filter($pics);
			$pic_arr = [];
			if (count($pics) > 2){
				foreach ($pics as $kkk =>  $pic) {
					$pic_arr[$kkk] = trim($pic);
				}
			}else{
				$d[$key]->type_id = $value->type_id > 1 ? 2 : 1;
			}
			$pic_arr = array_slice($pic_arr, 0, 5);  
			$d[$key]->pics = $pic_arr;
		}

		// $count = NewsService::getList($raw, TRUE);
		//$count = NewsService::count();
		$d = array_values($d);
		$assign = [
			'total' => 320,
			'list'  => $d
		];
		return $this->echoJson($assign);
    }

	/**
	 * [testAction 列表]
	 * @return [type] [description]
	 */
    public function testAction()
    {
    	$this->getUser(0);

		$raw = $this->validation(new ListValidation, $this->request->getJsonRawBody());
		$raw->city_id = $this->city_id;
		$raw->is_display = self::DISPLAY_TRUE;
		$raw->member_id = property_exists($raw,'member_id') ? $raw->member_id : 0;
		$data = NewsService::getList($raw);

		//获取点赞和收藏
		$praise_data = [];
		$collect_data = [];
		if ($raw->member_id && $raw->member_id >0 && count($data->toArray()) > 0){
			$groupId = 2;
			$id_arr = array_map('parent::getIdArray',$data->toArray());
			$praise_data  = MemberPraiseService::jugePraiseArr($raw->member_id, $groupId, $id_arr);
			$collect_data = MemberCollectService::jugeCollectArr($raw->member_id, $groupId, $id_arr);
		}

		$d = [];
		foreach ($data as $key => $value) {
			unset($value->index_by);
			unset($value->reco_by);
			$d[$key] = $value;

			$d[$key]->is_collect = intval($value->is_collect) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;

			$album = [];
			if ($value->type_id == 5)
				$album = json_decode($value->album);

			$d[$key]->album = $album;

			//判断缩略图是否有图且url是否完整
			$d[$key]->thumb = $value->thumb ? $this->getFullUrl($value->thumb, FALSE, $this->config->imgurl) : $this->config->imgurl . '/uploads/default.png';

			$d[$key]->num  = (string)count($d[$key]->album);
			unset($d[$key]->ads_url_ios);
			unset($d[$key]->ads_url);
			$d[$key]->comment = $value->comment > 10000 ? floor($value->comment / 10000) . '万+' : $value->comment;
			$d[$key]->visit = $value->visit > 10000 ? floor($value->visit / 10000) . '万+' : $value->visit;
			$d[$key]->sources = $value->sources ? $value->sources : "觅窝";

			if (strtotime($value->create_time) < strtotime(date("Y-m-d", time())) && $value->tags == 'new')
				$value->tags = '';
			// $d[$key]->ads_url = $value->create_time;
			// $d[$key]->ads_url_ios = date("Y-m-d H:i:s", time());
			$d[$key]->create_time = $this->getShowTime($value->create_time);
			$d[$key]->tags = $value->tags ? $value->tags : "";

			$d[$key]->is_praise  = in_array($value->id, $praise_data) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;
			$d[$key]->is_collect = in_array($value->id, $collect_data) ? (string)self::COLLECT_TRUE : (string)self::COLLECT_FALSE;

			$d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id;
			if ($value->cont_type != 1){//广告类的资讯
				$d[$key]->go_url = $value->ads_url;
			}else{
				$is_praise = $d[$key]->is_praise ? 1 : 0;
				// $d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id . '/' . $value->groupId . '/' . $is_praise;
				$d[$key]->go_url = $this->config->gourl . $this->config->urls->news . $value->id;
			}
			
			//第三方url
			$d[$key]->three_url = $value->three_url ? $value->three_url : $d[$key]->go_url;
			$value->pics ="";
			$pics = [];
			$pics = explode(',', $value->pics);
			$pics = array_filter($pics);
			$pic_arr = [];
			if (count($pics) > 2){
				foreach ($pics as $kkk =>  $pic) {
					$pic_arr[$kkk] = trim($pic);
				}
			}else{
				$d[$key]->type_id = $value->type_id > 1 ? 2 : 1;
			}
			$pic_arr = array_slice($pic_arr, 0, 5);  
			$d[$key]->pics = $pic_arr;
		}

		// $count = NewsService::getList($raw, TRUE);
		$count = NewsService::count();
		$assign = [
			'total' => $count,
			'list'  => $d
		];
		return $this->echoJson($assign);
    }
	
	/**
	 * [detailAction 详情]
	 * @return [type] [description]
	 */
    public function detailAction()
    {
    	$this->getUser(0);

		$id = $this->dispatcher->getParam('id');
		if (!$id)
			return $this->echoJson();
		
		if (isset($this->user)){
			$data = NewsService::getInfo($id, $this->user->member_id);
		}else{
			$data = NewsService::getInfo($id);
		}
		if (is_object($data)){
			//判断缩略图是否有图且url是否完整
			// $data->thumb = $data->thumb ? $this->getFullUrl($data->thumb, FALSE, $this->config->imgurl) : $this->config->imgurl . '/uploads/default.png';
			$data->pics = explode(',', $data->pics);
			$data->pics = array_filter($data->pics);
			$data->album = (array)json_decode($data->album);
			$data->content = $data->content ? $data->content : "";
			$data->go_url = $this->config->gourl . $this->config->urls->news . $data->id;
			//第三方房源url
			$data->three_url = $data->three_url ? $data->three_url : $data->go_url;
			$data->comment = $data->comment > 10000 ? floor($data->comment / 10000) . '万+' : $data->comment;
			$data->visit = $data->visit > 10000 ? floor($data->visit / 10000) . '万+' : $data->visit;
			$data->sources = $data->sources ? $data->sources : "觅窝";
			$preg = "|(.*)。|isU";
	    	$size = 200;
	    	$summary = self::summary($data->content, $size);
	    	preg_match($preg,strip_tags($summary),$match);
	    	$summary = current($match) ? $match[0] : "";
	    	$data->summary = trim($data->summary) ? trim($data->summary) : $summary;
		}			

		return  $this->echoJson($data);
    }

    public function summaryAction()
    {
    	$id = $this->dispatcher->getParam('id');
    	$data = NewsService::getInfo($id);

    	$preg = "|(.*)。|isU";
    	$size = 200;
    	$summary = self::summary($data->content, $size);
    	preg_match($preg,strip_tags($summary),$match);
    	$data->summary = trim($data->summary) ? trim($data->summary) : $match[0];
    	return $this->echoJson($data);
    }

   	/** 
	* 生成摘要 
	* @param (string) $body 
	*  正文 
	* @param (int) $size 
	*  摘要长度 
	* @param (int) $format 
	*  输入格式 id 
	*/   
	private function summary($body, $size, $format = NULL)
	{  
		$_size = mb_strlen($body, 'utf-8');  
		if($_size <= $size) 
			return $body;  
		// 输入格式中有 PHP 过滤器  
		// if(!isset($format) && filter_is_php($format))  
		//   return $body;  
	 	$strlen_var = strlen($body); 

	 	// 不包含 html 标签  
	 	if(strpos($body, '<') === false)
	 		return mb_substr($body, 0, $size);

	 	// 包含截断标志，优先  
	 	if($e = strpos($body, '<!-- break -->'))
	 		return mb_substr($body, 0, $e);  

	 	// html 代码标记  
	 	$html_tag = 0;  
	 	// 摘要字符串  
	 	$summary_string = '';  
		//数组用作记录摘要范围内出现的 html 标签 
		//开始和结束分别保存在 left 和 right 键名下
		//如字符串为：<h3><p><b>a</b></h3>，假设 p 未闭合
		//数组则为：array('left' => array('h3', 'p', 'b'), 'right' => 'b', 'h3'); 
		//仅补全 html 标签，<? <% 等其它语言标记，会产生不可预知结果 
	 	$html_array = ['left' => [], 'right' => []];  
	 	for($i = 0; $i < $strlen_var; ++$i) {  
		   	if(!$size) 
		   		break;  

	   		$current_var = substr($body, $i, 1);  
		   	if($current_var == '<'){  
		     	// html 代码开始  
		     	$html_tag = 1;  
		     	$html_array_str = '';

		   	}else if($html_tag == 1){  // 一段 html 代码结束 

		     	if($current_var == '>'){  //去除首尾空格，如 <br /  > < img src="" / > 等可能出现首尾空格 

			       	$html_array_str = trim($html_array_str);  //判断最后一个字符是否为 /，若是，则标签已闭合，不记录 
			        
			       	if(substr($html_array_str, -1) != '/'){ // 判断第一个字符是否 /，若是，则放在 right 单元 

		         		$f = substr($html_array_str, 0, 1); 

		         		if($f == '/'){ // 去掉 /  

		           			$html_array['right'][] = str_replace('/', '', $html_array_str);  
		  
		         		}else if($f != '?'){  // 判断是否为 ?，若是，则为 PHP 代码，跳过  

							//判断是否有半角空格，若有，以空格分割，第一个单元为 html 标签 如 <h2 class="a"> <p class="a"> 
			           		if(strpos($html_array_str, ' ') !== false){  
			  
			             	//分割成2个单元，可能有多个空格，如：<h2 class="" id="">  
			             	$html_array['left'][] = strtolower(current(explode(' ', $html_array_str, 2)));  
			  
			           		}else{ 

			           			//若没有空格，整个字符串为 html 标签，如：<b> <p> 等 // 统一转换为小写 
			             		$html_array['left'][] = strtolower($html_array_str);  
			           		}  
		  
		         		}  
		       		} 
		       		// 字符串重置  
		       		$html_array_str = '';  
		       		$html_tag = 0;  
		     	}else{  
		  			
		       		$html_array_str .= $current_var;//将< >之间的字符组成一个字符串 用于提取 html 标签   
		     	}  
		   	}else{  
		    	--$size;// 非 html 代码才记数    
		   	}  

	   		$ord_var_c = ord($body{$i});  
		   	switch (true) {  

		     	case (($ord_var_c & 0xE0) == 0xC0):  
		       		// 2 字节  
		       		$summary_string .= substr($body, $i, 2);  
		       		$i += 1;  
		     	break;  

		  		case (($ord_var_c & 0xF0) == 0xE0):  
		       		// 3 字节  
		       		$summary_string .= substr($body, $i, 3);  
		       		$i += 2;  
		     	break;  
		  
		     	case (($ord_var_c & 0xF8) == 0xF0):  
		       		// 4 字节  
		       		$summary_string .= substr($body, $i, 4);  
		       		$i += 3;  
		     	break;

		     	case (($ord_var_c & 0xFC) == 0xF8):  
		       		// 5 字节  
		       		$summary_string .= substr($body, $i, 5);  
		       		$i += 4;  
		     	break; 

		     	case (($ord_var_c & 0xFE) == 0xFC):  
		       		// 6 字节  
		       		$summary_string .= substr($body, $i, 6);  
		       		$i += 5;  
		     	break; 

		     	default:  
		       		// 1 字节  
		       		$summary_string .= $current_var;  
		   	}  
		  
		}  
 		//比对左右 html 标签，不足则补全  
		if($html_array['left']){  
		   /** 
		    * 交换 left 顺序，补充的顺序应与 html 出现的顺序相反 
		    * 如待补全的字符串为：<h2>abc<b>abc<p>abc 
		    * 补充顺序应为：</p></b></h2> 
		    */  
		 	$html_array['left'] = array_reverse($html_array['left']);  
		   	foreach($html_array['left'] as $index => $tag){  
		    	// 判断该标签是否出现在 right 中  
		    	$key = array_search($tag, $html_array['right']);  
		    	if($key !== false){  
		  			// 出现，从 right 中删除该单元  
		    		unset($html_array['right'][$key]);  
		    	}else{  
		   			// 没有出现，需要补全  
		    		$summary_string .= '</'.$tag.'>';  
		     	}  
		   	}  
		}  
	 	return $summary_string;  
	}  

}